<template>
  <t-dialog
    :visible="visible"
    :header="isEdit ? '编辑规则' : '新增规则'"
    width="600px"
    top="5vh"
    @confirm="handleSubmit"
    @cancel="handleClose"
    :confirm-btn="{ loading: submitLoading }"
    @close="handleClose"
  >
    <div class="add-rule-form">
      <t-form
        ref="formRef"
        :data="formData"
        :rules="formRules"
        label-align="right"
        label-width="80px"
        class="rule-form"
      >
        <t-form-item label="规则标题" name="title">
          <t-input
            v-model="formData.title"
            placeholder="请输入规则标题"
            clearable
          />
        </t-form-item>

        <t-form-item label="规则描述" name="description">
          <t-textarea
            v-model="formData.description"
            placeholder="请输入规则描述"
            show-limit
            :autosize="{ minRows: 3, maxRows: 6 }"
          />
        </t-form-item>

        <t-form-item label="完成次数" name="completionCount">
          <t-input-number
            v-model="formData.completionCount"
            placeholder="请输入完成次数"
            :min="1"
            :max="9999"
            theme="normal"
            style="width: 100%"
          />
        </t-form-item>

        <t-form-item label="奖励积分" name="rewardPoints">
          <t-input-number
            v-model="formData.rewardPoints"
            placeholder="请输入奖励积分"
            :min="1"
            :max="99999"
            theme="normal"
            style="width: 100%"
          />
        </t-form-item>
      </t-form>
    </div>
  </t-dialog>
</template>

<script>
import { MessagePlugin } from 'tdesign-vue';
import { createRules, updateRules } from '@/api/rules';

export default {
  name: 'AddRuleDialog',
  model: {
    prop: 'visible',
    event: 'update:visible'
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: () => null
    }
  },
  emits: ['update:visible', 'success'],
  data() {
    return {
      submitLoading: false,

      // 表单数据
      formData: {
        title: '',
        description: '',
        completionCount: 1,
        rewardPoints: 10
      },

      // 表单验证规则
      formRules: {
        title: [
          { required: true, message: '请输入规则标题', trigger: 'blur' },
          { min: 2, max: 50, message: '规则标题长度应在2-50个字符之间', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入规则描述', trigger: 'blur' }
        ],
        completionCount: [
          { required: true, message: '请输入完成次数', trigger: 'blur' },
          { type: 'number', min: 1, max: 9999, message: '完成次数应在1-9999之间', trigger: 'blur' }
        ],
        rewardPoints: [
          { required: true, message: '请输入奖励积分', trigger: 'blur' },
          { type: 'number', min: 1, max: 99999, message: '奖励积分应在1-99999之间', trigger: 'blur' }
        ]
      }
    };
  },

  watch: {
    visible: {
      handler(newVal) {
        if (newVal) {
          this.resetForm();
          // 如果是编辑模式且有编辑数据，则填充表单
          if (this.isEdit && this.editData) {
            this.fillFormData();
          }
        }
      },
      immediate: true,
    },
  },

  methods: {
    // 关闭弹框
    handleClose() {
      this.$emit('update:visible', false);
      this.resetForm();
    },

    // 重置表单
    resetForm() {
      this.formData = {
        title: '',
        description: '',
        completionCount: 1,
        rewardPoints: 10
      };

      this.$nextTick(() => {
        this.$refs.formRef?.clearValidate();
      });
    },

    // 填充编辑数据到表单
    fillFormData() {
      if (this.editData) {
        this.formData = {
          title: this.editData.title || '',
          description: this.editData.description || '',
          completionCount: this.editData.completionCount || 1,
          rewardPoints: this.editData.rewardPoints || 10
        };
      }
    },

    // 提交表单
    async handleSubmit() {
      try {
        // 验证表单
        const valid = await this.$refs.formRef.validate();
        if (valid !== true) {
          return;
        }

        this.submitLoading = true;

        // 准备提交数据
        const submitData = {
          ruleName: this.formData.title,
          description: this.formData.description,
          targetCount: this.formData.completionCount,
          fixedPoints: this.formData.rewardPoints
        };

        let response;

        if (this.isEdit && this.editData?.id) {
          // 编辑模式 - 调用更新接口
          response = await updateRules(this.editData.id, submitData);

          if (response && (response.code === 200 || response.data?.code === 200)) {
            MessagePlugin.success('规则更新成功');
            this.$emit('success', {
              ...submitData,
              id: this.editData.id,
              value: this.editData.id
            });
            this.handleClose();
          } else {
            throw new Error(response?.message || response?.data?.message || '更新失败');
          }
        } else {
          // 新增模式 - 调用创建接口
          const createSubmitData = {
            ...submitData,
            ruleType: 'FIXED',
            rewardType: 'PER_ATTEMPT'
          };

          response = await createRules(createSubmitData);

          if (response && response.data && response.data.code === 200) {
            MessagePlugin.success('规则创建成功');
            this.$emit('success', response.data.data);
            this.handleClose();
          } else {
            throw new Error(response?.data?.message || '创建失败');
          }
        }
      } catch (error) {
        console.error(this.isEdit ? '更新规则失败:' : '创建规则失败:', error);
        MessagePlugin.error(error.message || (this.isEdit ? '更新规则失败' : '创建规则失败'));
      } finally {
        this.submitLoading = false;
      }
    }
  }
};
</script>

<style lang="less" scoped>
.add-rule-form {
  padding: 16px 0;
}

.rule-form {
  width: 100%;
}
</style>